<?php

/**
 * Check field is dupplicate
 */

class DupplicateValidator extends CValidator {

    public $tableName;
    public $isNewRecord;
    public $currId;

    protected function validateAttribute($object, $attribute) {
        $value = $object->$attribute;
        
        if ( ! empty($value) ) {
            $existId = Yii::app()->db->createCommand()
                ->select('id')
                ->from($this->tableName)
                ->where("$attribute=:attr", array(':attr' => $value))
                ->queryScalar();

            if ( $existId && (($this->isNewRecord) || ($this->currId != $existId)) ) {
                $errorMsg = ($this->message !== null) ?
                    $this->message
                    :
                    Yii::t('DadminModule.msg', 'input_dupplicate_value', array(
                        '{0}' => '{attribute}',
                    ));
                $this->addError($object, $attribute, $errorMsg);
            }
        }
        return TRUE;
    }

}